import {isObject, isString} from "./TypeUtil";
import {formatStr} from "./StringUtil";
import {getObjByRule} from "./ObjUtil";

const commonKeys = ["id", "ids", "type", "bdmsExtendPrefName", "bdmsModuleName", "bdmsAuthMenu", "targetId", "targetIds", "extendAction"];

/**
 * 创建请求参数
 * @param options 包含flowData, pName, valKey, extend, dataSource, isBatch, url
 *                  请参考下方BatchSubmit组件说明
 * @return {{url: String, params: {}}}
 */
interface OptionsProps {
    url?: string,
    method?: string,
    row?: any,
    flowData?: any[],
    pName?: any,
    valKey?: any,
    extend?: any,
    dataSource: any,
    isBatch?: boolean,
    isFormatChild?: boolean,
    expandAttrKey?: string,
    selectData: any[],
    selectExtend?: any,
    otherCommonKeys?: string[],
    joinStr?: string,
}

// @ts-ignore
let getParams: Function = (row: any, valKey: any): any => {
    if (!row) {
        return {}
    }
    if (isString(valKey)) {
        return valKey.indexOf("$") !== -1 ? formatStr(valKey, row) : row[valKey];
    }
    let result: any = {};
    for (let k in valKey) {
        result[k] = valKey[k].indexOf("$") !== -1 ? formatStr(valKey[k], row) : row[valKey[k]];
    }
    return result;
};

// @ts-ignore
const createFetchParams: Function = (options: OptionsProps): object => {
    let {
            flowData = [],
            selectData = [],
            selectExtend,
            isFormatChild,
            pName = "",
            valKey = "id",
            method,
            extend,
            dataSource = {},
            isBatch,
            url,
            expandAttrKey,
            otherCommonKeys,
            joinStr
        } = options,
        // 最终使用的url
        newUrl = url;
    // 提交参数
    let submitParams: any = {};
    let data: any [] = flowData;
    if (extend) {
        // 是字符串则去datasource中找对应的对象
        if (isString(extend)) {
            submitParams = {...dataSource[extend]}
        } else if (isObject(extend)) {
            for (let key in extend) {
                if (isString(extend[key]) && extend[key].indexOf("$") !== -1) {
                    // submitParams[key] = isBatch === false ? getParams({...(data[0] || {}), ...dataSource}, extend[key]) : data.map((item: any = {}) => (getParams({...item, ...dataSource}, extend[key])))
                    submitParams[key] = formatStr(extend[key], {...(flowData[0] || {}), ...dataSource});
                } else {
                    submitParams[key] = extend[key];
                }
            }
        }
    }
    if (pName && data.length) {
        if (isString(valKey)) {
            submitParams[pName] = isBatch === false ? getParams(data[0], valKey) : data.map((item: any) => (getParams(item, valKey)));
            if (joinStr) {
                submitParams[pName] = submitParams[pName].join(joinStr)
            }
        } else {
            submitParams[pName] = isBatch === false ? getObjByRule(data[0], valKey, false, isFormatChild) : data.map((item: any) => (getObjByRule(item, valKey, false, isFormatChild)));
        }
    }
    if (selectExtend && selectData && selectData.length) {
        const {pName = "ids", valKey = "id", isBatch}: {
            pName: string,
            valKey: any,
            isBatch: boolean | undefined
        } = selectExtend;
        if (isString(valKey)) {
            submitParams[pName] = isBatch === false ? getParams(selectData[0], valKey) : selectData.map((item: any) => (getParams(item, valKey)));
        } else {
            submitParams[pName] = isBatch === false ? getObjByRule(selectData[0], valKey, false, isFormatChild) : selectData.map((item: any) => (getObjByRule(item, valKey, false, isFormatChild)));
        }
    }
    if (expandAttrKey) {
        submitParams = formatCommonParams(submitParams, expandAttrKey, otherCommonKeys)
    }
    return {
        url: newUrl,
        method,
        params: submitParams
    };
};


// @ts-ignore
const createParams: Function = (params: any = {}, options: OptionsProps): object => {
    let {flowData = [], extend, dataSource = {}, expandAttrKey = "", otherCommonKeys = []} = options;
    let newParams: any = {...params};
    if (extend) {
        // 是字符串则去datasource中找对应的对象
        if (isString(extend)) {
            newParams = {...dataSource[extend]}
        } else if (isObject(extend)) {
            for (let key in extend) {
                let value: any;
                if (isString(extend[key]) && extend[key].indexOf("$") !== -1) {
                    value = formatStr(extend[key], {
                        row: options.row || {},
                        flowData: (flowData[0] || {}), ...dataSource
                    });
                } else {
                    value = extend[key];
                }
                newParams[key] = value;
            }
        }
    }
    if (expandAttrKey) {
        newParams = formatCommonParams(newParams, expandAttrKey, otherCommonKeys);
    }
    return newParams;
};
// @ts-ignore
const formatCommonParams: Function = (params: any = {}, expandAttrKey: string = "extendAttrs", otherCommonKeys: string[] = []) => {
    let formatParams: any = {
        [expandAttrKey]: params[expandAttrKey] ? {...params[expandAttrKey]} : {}
    };
    for (let k in params) {
        if ([...commonKeys, ...otherCommonKeys].indexOf(k) !== -1) {
            formatParams[k] = params[k] !== null ? params[k] : "";
        } else {
            formatParams[expandAttrKey][k] = params[k] !== null ? params[k] : "";
        }
    }
    return formatParams;

    let a = {
        view: "col_common_name_list",
        tableApi: {
            url: "/sf-drs/outbound/supplier/listSupplierTree",
            params: {showMark: "DEFAULT"},
            rowKey: "xoid",
            format: {
                key: "id",
                label: "name"
            },
            otherProps: {
                isTreeTable: true,
                isLazyData: true,
                autoExpand: true
            }
        },
        rightTableProps: {
            view: "col_common_name_list",
            tableApi: {
                url: "/sf-drs/platform/view/getAllViews"
            }
        },
        url: "/sf-drs/outbound/changeNoticeSend/sendChangeContent",
        method: "POST",
        pName: "contentIds",
        valKey: "id",
        extend: {changeNoticeId: "${ds.row.id}"},
        selectExtend: {pName: "suppIds", valKey: "xoid"},
        rightExtend: {
            pName: "info", valKey: {
                datasetId: "datasetId",
                fileLinkId: "fileLinkId"
            }
        },
    }


}

export {
    getParams,
    createParams,
    createFetchParams,
    formatCommonParams
};